/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include "attachment.h"
#include "mimetypes.h"
#include "log.h"

namespace Wishmaster
{
	AttachmentPtr Attachment::create(const QUrl& thumblink, const QUrl& link, const QByteArray& data)
	{
		return AttachmentPtr(new Attachment(thumblink, link, data));
	}

	Attachment::Attachment(const QUrl& thumblink, const QUrl& link, const QByteArray& data) :
		m_data(data),
		m_url(link),
		m_thumbUrl(thumblink)
	{
		m_type = detectType(link);
	}

	Attachment::~Attachment()
	{
	}

	void Attachment::setThumbnail(const QImage& image)
	{
		m_thumbnail = image;
	}

	QImage Attachment::thumbnail()
	{
		return m_thumbnail;
	}

	void Attachment::setThumnailUrl(const QUrl& url)
	{
		m_thumbUrl = url;
	}

	QUrl Attachment::thumbnailUrl()
	{
		return m_thumbUrl;
	}

	void Attachment::setData(const QByteArray& data)
	{
		m_data = data;
	}

	QByteArray Attachment::data()
	{
		return m_data;
	}

	void Attachment::setUrl(const QUrl& url)
	{
		m_url = url;
		m_type = detectType(url);
	}

	QUrl Attachment::url()
	{
		return m_url;
	}

	QString Attachment::filename()
	{
		QString path = m_url.path();
		if(path.isEmpty())
			return path;
		return path.mid(path.lastIndexOf('/') + 1);
	}

	QImage Attachment::image()
	{
		if(m_type.startsWith("image") &&
				m_image.isNull() &&
				!m_data.isEmpty())
		{
			m_image = QImage::fromData(m_data);
		}
		return m_image;
	}

	QString Attachment::detectType(const QUrl& link)
	{
		QString ext = link.path().mid(link.path().lastIndexOf('.') + 1).toLower();
		QString type = MimeTypes::instance()->typeForExtension(ext);
		if(!type.isEmpty())
			return type;
		return "application/octet-stream";
	}

	void Attachment::setType(const QString& type)
	{
		m_type = type;
	}

	QString Attachment::type()
	{
		return m_type;
	}

	bool Attachment::hasThumbnail() const
	{
		return !m_thumbnail.isNull();
	}

	bool Attachment::hasData() const
	{
		return (m_data.size() > 0) || (!m_image.isNull());
	}
}

